package com.yonyou.cyxdms.basedata.service.service.color;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.lang.Assert;
import com.yonyou.cloud.http.plus.remote.IRemoteInvoke;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.service.excel.ExcelRead;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataDictConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.ColorCacheCMSVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.ColorCacheVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.ColorVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.MQBaseVO;
import com.yonyou.cyxdms.basedata.service.constant.BasedataCommonConstants;
import com.yonyou.cyxdms.basedata.service.constant.BasedataDictConstants;
import com.yonyou.cyxdms.basedata.service.dto.CarInfoDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.*;
import com.yonyou.cyxdms.basedata.service.entity.color.ColorPO;
import com.yonyou.cyxdms.basedata.service.repository.basedata.SystemParamMapper;
import com.yonyou.cyxdms.basedata.service.repository.color.ColorMapper;
import com.yonyou.cyxdms.basedata.service.service.brand.BrandService;
import com.yonyou.cyxdms.basedata.service.util.EasyPoiUtil;
import com.yonyou.cyxdms.basedata.service.util.MQUtils;
import com.yonyou.cyxdms.basedata.service.util.MapUtils;
import com.yonyou.cyxdms.basedata.service.vo.CarInfoVO;
import com.yonyou.cyxdms.basedata.service.vo.CarparamColorVO;
import com.yonyou.cyxdms.basedata.service.vo.ExportMsgVO;
import com.yonyou.cyxdms.basedata.service.vo.color.ColorsVO;
import com.yonyou.cyxdms.basedata.service.vo.color.ExteriorAndInteriorColorVO;
import com.yonyou.cyxdms.basedata.service.vo.color.PageColorVO;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysmanage.client.service.login.DealerBrandService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ColorServiceImpl
 *
 * @author: guorp
 * @since: 2018/12/14
 * @updateDate:
 * @updateRemark:
 * @version:1.0 Copyright: Copyright (c) 2018
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ColorServiceImpl implements ColorService {

    public static final Logger logger = LoggerFactory.getLogger(ColorServiceImpl.class);

    @Autowired
    ColorMapper colorMapper;

    @Autowired
    private BrandService brandService;

    @Autowired
    DealerBrandService dealerBrandService;

    @Autowired
    SystemParamMapper systemParamMapper;

    @Autowired
    IRemoteInvoke iRemoteInvoke;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private ExcelRead<ColorImportDTO> excelColorService;

    /**
     * 根据packageId查询颜色
     *
     * @param packageId
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.CarColorDTO>
     * @author guorp
     * @since 2018/12/14
     */
    @Override
    public List<ColorVO> getColorByPackageId(Long packageId) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return colorMapper.getColorByPackageId(packageId, loginInfo.getAppId(), loginInfo.getGroupCode(), loginInfo.getOwnerCode());
    }
    
    /**
     * 根据optionId查询颜色
     *
     * @param optionId
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.CarColorDTO>
     * @author zys
     * @since 2020/2/10
     */
    @Override
    public List<ColorVO> getColorByPackageIdV2(Long optionId) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return colorMapper.getColorByPackageIdV2(optionId, loginInfo.getAppId(), loginInfo.getGroupCode(), loginInfo.getOwnerCode());
    }

    /**
     * 查询所有颜色
     *
     * @param
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.dto.basedata.CarColorDTO>
     * @author renwd
     * @since 2019/2/28
     */
    @Override
    public List<ColorVO> listColor() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return colorMapper.listColor(BaseDataDictConstants.IS_VALID, loginInfo.getOwnerCode());
    }

    /**
     * 按条件查询颜色信息
     *
     * @param queryParam 查询条件
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.ColorCacheVO>
     * @author renwd
     * @since 2018/12/18
     */
    @Override
    @Transactional(readOnly = true)
    public List<ColorCacheVO> queryColorByCondition(Map<String, Object> queryParam) {
        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
        queryParam.put("brandIdList", brandIdList);

        return colorMapper.queryColorByCondition(queryParam);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ColorCacheCMSVO> queryColorByConditionCms(Map<String, Object> queryParam) {
        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
        if(brandIdList.size()>0){
            queryParam.put("brandIdList", brandIdList);
        }

        return colorMapper.queryColorByConditionCms(queryParam);
    }


    /**
     * 根据车系id或车型id或配置id或颜色id查询车型信息
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.CarInfoVO>
     * @author renwd
     * @since 2019/6/25
     */
    @Override
    public CarInfoVO selectCarInfoByCondition(CarInfoDTO queryParam) {
        return colorMapper.carInfoByCondition(queryParam);
    }

    /**
     * 根据车系Id检索车型颜色列表
     *
     * @param carId
     * @return (non - Javadoc)
     * @author Zhangsx
     * @date 2018年9月7日
     */
    @Override
    public List<CarparamColorVO> queryCarColor(Long carId) {
        LambdaQueryWrapper<ColorPO> queryWrapper = new QueryWrapper<ColorPO>().lambda();
        // 颜色信息中没有车型ID
        //获取loginInfoDto
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appid = loginInfoDto.getAppId();
        logger.debug("appid:{}", appid);
        queryWrapper.eq(ColorPO::getAppId, appid);
        List<ColorPO> list = colorMapper.selectList(queryWrapper);
        List<CarparamColorVO> colorVos = new ArrayList<>();
        for (ColorPO carparamcolorPo : list) {
            CarparamColorVO carparamColorVo = new CarparamColorVO();
            carparamColorVo.setColorId(carparamcolorPo.getColorId());
            carparamColorVo.setColorName(carparamcolorPo.getColorName());
            colorVos.add(carparamColorVo);
        }
        return colorVos;
    }

    /**
     * 根据车型Id  颜色Id 检索指导价格
     *
     * @param carId
     * @param colorId
     * @return (non - Javadoc)
     * @author Zhangsx
     * @date 2018年9月7日
     */
    @Override
    public Double queryPrice(Long carId, Integer colorId) {
        LambdaQueryWrapper<ColorPO> queryWrapper = new QueryWrapper<ColorPO>().lambda();
        // 这里DMS的颜色中没有车型
        queryWrapper.eq(ColorPO::getColorId, colorId);

        //获取loginInfoDto
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appid = loginInfoDto.getAppId();
        logger.debug("appid:{}", appid);
        queryWrapper.eq(ColorPO::getAppId, appid);
        List<ColorPO> list = colorMapper.selectList(queryWrapper);
        if (list.size() != 1) {
            throw new BeanInitializationException("车型报价数据异常，请重试");
        }
        // DMS的颜色中没有报价信息
        return null;
    }

    /**
     * 分页查询车辆颜色
     *
     * @param page
     * @param colorQueryDTO
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public IPage<PageColorVO> queryColor(Page page, ColorQueryDTO colorQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = colorQueryDTO.toMaps();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询颜色IPage的queryParam:---------{}", queryParam);
        page.setRecords(colorMapper.pageColor(page, queryParam));
        return page;
    }

    /**
     * 分页查询Dcs车辆颜色
     *
     * @param page
     * @param colorQueryDTO
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public IPage<PageColorVO> queryDcsColor(Page page, ColorQueryDTO colorQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = colorQueryDTO.toMaps();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询颜色IPage的queryParam:---------{}", queryParam);
        page.setRecords(colorMapper.pageDcsColor(page, queryParam));
        return page;
    }

    /**
     * 修改颜色
     *
     * @param id
     * @param colorDto
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/16
     */
    @Override
    public Integer updateColor(Long id, CarColorDTO colorDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        ColorPO colorPo = colorMapper.selectById(id);
        if (colorPo != null) {
            QueryWrapper<ColorPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .in(ColorPO::getOwnerCode, loginInfoDto.getOwnerCode())
                    .eq(ColorPO::getAppId, loginInfoDto.getAppId())
                    .eq(ColorPO::getColorType, colorDto.getColorType())
                    .notIn(ColorPO::getColorId, colorPo.getColorId())
                    .and(obj ->
                            obj.eq(ColorPO::getColorCode, colorDto.getColorCode())
                                    .or()
                                    .eq(ColorPO::getColorName, colorDto.getColorName()));
            // 只判断本店面相同颜色类型的代码和名称是否重复
            List<ColorPO> colorPos = colorMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(colorPos)) {
                throw new ServiceBizException(BasedataCommonConstants.COLOR_NOT_REPEAT);
            }
            colorPo.setColorType(colorDto.getColorType());
            colorPo.setColorCode(colorDto.getColorCode());
            colorPo.setColorName(colorDto.getColorName());
            colorPo.setIsValid(colorDto.getIsValid());
            colorPo.setDataSources(colorDto.getDataSources());
            colorPo.setRecordVersion(colorDto.getRecordVersion());
            int updateSize = colorMapper.updateById(colorPo);
            if (updateSize != 0) {
                // 删除redis缓存
                String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
                redisClient.del(productFormat);
                // 数据发送到MQ
                sendColor(colorPo, BasedataCommonConstants.BIZ_COLOR_UPDATE);
                return updateSize;
            } else {
                throw new ServiceBizException(BasedataCommonConstants.UPDATE_FAILED);
            }
        } else {
            throw new ServiceBizException("不存在该车辆颜色！");
        }

    }

    /**
     * Dcs修改颜色
     *
     * @param id
     * @param colorDto
     * @return java.lang.Integer
     * @author lijun
     * @since 2019/11/16
     */
    @Override
    public Integer updateDcsColor(Long id, CarColorDTO colorDto) {
        String appId = BasedataCommonConstants.APP_ID_RL;
        String groupCode = "-1";
        ColorPO colorPo = colorMapper.selectById(id);
        if (colorPo != null) {
            QueryWrapper<ColorPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(ColorPO::getAppId, appId)
                    .eq(ColorPO::getColorType, colorDto.getColorType())
                    .notIn(ColorPO::getColorId, colorPo.getColorId())
                    .and(obj ->
                            obj.eq(ColorPO::getColorCode, colorDto.getColorCode()));
            // 只判断本店面相同颜色类型的代码和名称是否重复
            List<ColorPO> colorPos = colorMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(colorPos)) {
                throw new ServiceBizException(BasedataCommonConstants.COLOR_NOT_REPEAT);
            }
            colorPo.setColorName(colorDto.getColorName());
            int updateSize = colorMapper.updateById(colorPo);
            if (updateSize != 0) {
                // 删除redis缓存
                String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, appId, BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
                redisClient.del(productFormat);
                // 数据发送到MQ
//                sendColor(colorPo, BasedataCommonConstants.BIZ_COLOR_UPDATE);
                return updateSize;
            } else {
                throw new ServiceBizException(BasedataCommonConstants.UPDATE_FAILED);
            }
        } else {
            throw new ServiceBizException("不存在该车辆颜色！");
        }
    }

    /**
     * 颜色数据发送到MQ
     *
     * @param colorPo
     * @author ysj
     * @date 2019/10/23
     */
    public void sendColor(ColorPO colorPo, String bizId) {
        List<ColorPO> colorList = new ArrayList<>();
        colorList.add(colorPo);
        MQBaseVO<List<ColorPO>> colorMq = new MQBaseVO<>(colorList, colorPo.getAppId(), colorPo.getOwnerCode());
        MQUtils.sendMsg(colorMq.toMap(), bizId, systemParamMapper,iRemoteInvoke);
    }

    /**
     * 新增颜色
     *
     * @param carColorDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/16
     */
    @Override
    public Integer addColor(CarColorDTO carColorDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<ColorPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(ColorPO::getOwnerCode, loginInfoDto.getOwnerCode())
                .eq(ColorPO::getAppId, loginInfoDto.getAppId())
                .eq(ColorPO::getColorType, carColorDTO.getColorType())
                .eq(ColorPO::getColorCode, carColorDTO.getColorCode())
                .eq(ColorPO::getColorName, carColorDTO.getColorName());
        // 判断同一家店面中相同颜色类型是否存在相同的颜色代码或名称
        List<ColorPO> colorPos = colorMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(colorPos)) {
            throw new ServiceBizException(BasedataCommonConstants.COLOR_NOT_REPEAT);
        }
        carColorDTO.setAppId(loginInfoDto.getAppId());
        carColorDTO.setOwnerCode(loginInfoDto.getOwnerCode());
        ColorPO colorPo = BeanMapperUtil.copyProperties(carColorDTO, ColorPO.class);
        int insertSize = colorMapper.insert(colorPo);
        // 删除redis缓存
        String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        redisClient.del(productFormat);
        // 数据发送到MQ
        sendColor(colorPo, BasedataCommonConstants.BIZ_COLOR_INSERT);
        return insertSize;
    }

    /**
     * Dcs新增颜色
     *
     * @param carColorDTO
     * @return java.lang.Integer
     * @author tansijun
     * @since 2019/11/16
     */
    @Override
    public Integer addDcsColor(CarColorDTO carColorDTO) {
        String appId = BasedataCommonConstants.APP_ID_RL;
        String groupCode = "-1";
        QueryWrapper<ColorPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ColorPO::getAppId, appId)
                .eq(ColorPO::getColorType, carColorDTO.getColorType())
                .and(obj ->
                        obj.eq(ColorPO::getColorCode, carColorDTO.getColorCode()));
        // 判断同一家店面中相同颜色类型是否存在相同的颜色代码或名称
        List<ColorPO> colorPos = colorMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(colorPos)) {
            return 0;
        }
        ColorPO colorPo = BeanMapperUtil.copyProperties(carColorDTO, ColorPO.class);
        colorPo.setDataSources(BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        colorPo.setAppId(BasedataCommonConstants.APP_ID_RL);
        colorPo.setCompanyCode("-1");
        colorPo.setOwnerCode("-1");
        colorPo.setOwnerParCode("-1");
        colorPo.setIsIssue(BasedataDictConstants.IS_NO_SEND);
        int insertSize = colorMapper.insert(colorPo);
        // 删除redis缓存
        String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, appId, BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
        redisClient.del(productFormat);
        return insertSize;
    }

    /**
     * 查询外饰内饰
     *
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.color.ExteriorAndInteriorColorVO>
     * @author renwd
     * @since 2019/7/18
     */
    @Override
    public List<ExteriorAndInteriorColorVO> selectExteriorColorInfo(Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put("orgType", loginInfo.getOrgType());
        return colorMapper.selectExteriorColorInfo(queryParam);
    }

    /**
     * 根据code查询颜色
     *
     * @param appId
     * @param colorCode
     * @return com.yonyou.cyxdms.basedata.service.entity.color.ColorPO
     * @author lijun
     * @since 2019/9/12
     */
    @Override
    public ColorPO getByCode(String appId, String colorCode) {
        return colorMapper.getByCode(appId, colorCode);
    }

    /**
     * 通用-新增/更新颜色
     *
     * @author：chenzb
     * @since：2019-10-12
     */
    @Override
    public void addColorGeneral(List<GeneralCarColorDTO> generalCarColorDtoS) {
        logger.debug("厂端同步至后台的车辆颜色数据:{}", generalCarColorDtoS);
        if (CollectionUtils.isNotEmpty(generalCarColorDtoS)) {
            // 数据不为空遍历存储
            for (GeneralCarColorDTO generalCarColorDTO : generalCarColorDtoS) {
                QueryWrapper<ColorPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(ColorPO::getAppId, generalCarColorDTO.getAppId())
                        .eq(ColorPO::getSourceId, generalCarColorDTO.getSourceId());
                ColorPO oldColorPo = colorMapper.selectOne(queryWrapper);
                String ownerCode = StringUtils.isBlank(generalCarColorDTO.getOwnerCode()) ? "-1" : generalCarColorDTO.getOwnerCode();
                // ownerCode设值-1 标记车厂下发
                if (oldColorPo == null) {
                    // 新增配置
                    ColorPO colorPo = BeanMapperUtil.copyProperties(generalCarColorDTO, ColorPO.class);
                    colorPo.setOwnerCode(ownerCode);
                    colorPo.setCompanyCode(ownerCode);
                    colorPo.setOwnerParCode(ownerCode);
                    colorPo.setSourceChangedAt(LocalDateTime.now());
                    colorPo.setCreatedAt(LocalDateTime.now());
                    colorPo.setIsValid(10041001);
                    logger.debug("开始新增插入车辆颜色数据:{}", colorPo);
                    colorMapper.insert(colorPo);
                } else {
                    // 更新配置
                    ColorPO colorPo = BeanMapperUtil.copyProperties(generalCarColorDTO, ColorPO.class);
                    colorPo.setOwnerCode(ownerCode);
                    colorPo.setCompanyCode(ownerCode);
                    colorPo.setOwnerParCode(ownerCode);
                    colorPo.setColorId(oldColorPo.getColorId());
                    colorPo.setUpdatedAt(LocalDateTime.now());
                    colorPo.setIsValid(generalCarColorDTO.getIsValid());
                    colorPo.setCreatedBy("-1");
                    colorPo.setRecordVersion(oldColorPo.getRecordVersion());
                    colorPo.setIsDeleted(generalCarColorDTO.getIsDelete() == null ? 0 : generalCarColorDTO.getIsDelete());
                    logger.debug("开始更新车辆颜色数据:{}", colorPo);
                    colorMapper.updateById(colorPo);
                }
            }
        } else {
            throw new ServiceBizException("厂端传来的颜色数据的缺失！");
        }
    }

    /**
     * 获取所有颜色
     *
     * @param colorType 16081002 外饰色,16081001内饰色
     * @return:
     * @auther: tanjie
     * @since: 2019/11/4
     */
    @Override
    public List<ColorCacheVO> getAllColorByAppIdAndType(String appId, Integer colorType) {
        LambdaQueryWrapper<ColorPO> query = new QueryWrapper<ColorPO>().lambda();
        query.eq(ColorPO::getAppId, appId);
        if (null != colorType) {
            query.eq(ColorPO::getColorType, colorType);
        }
        List<ColorPO> colorPos = this.colorMapper.selectList(query);
        String colorJson = JSONUtil.objectToJson(colorPos);
        return JSONUtil.jsonToObj(colorJson, new TypeReference<List<ColorCacheVO>>() {
        });
    }

    /**
     * 品牌导入
     *
     * @param rowDto
     * @return void
     * @author renwd
     * @since 2019/7/22
     */
    private void addColorImport(ColorImportDTO rowDto, boolean isValidateSucess) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<ColorPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ColorPO::getColorCode, rowDto.getColorCode())
                .eq(ColorPO::getColorName, rowDto.getColorName())
                .eq(ColorPO::getAppId, loginInfoDto.getAppId())
                .in(ColorPO::getOwnerCode, loginInfoDto.getOwnerCode(), loginInfoDto.getGroupCode(), "-1");
        List<ColorPO> list = colorMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(list)) {
            throw new ServiceBizException("颜色代码+颜色名称 不能重复");
        }

        ColorPO colorPo = new ColorPO();

        colorPo.setDataSources(10451002);//主机厂
        colorPo.setCreatedBy(loginInfoDto.getUserId().toString());
        String isValid = rowDto.getIsValid();
        if (StringUtils.isNotEmpty(isValid)) {
            colorPo.setIsValid(null);
        } else if ("是".equals(isValid)) {
            colorPo.setIsValid(10041001);
        } else if ("否".equals(isValid)) {
            colorPo.setIsValid(10041002);
        } else {
            throw new ServiceBizException("有效标识不存在");
        }

        String colorType = rowDto.getColorType();
        if (StringUtils.isNotEmpty(colorType)) {
            colorPo.setColorType(null);
        } else if ("内饰".equals(colorType)) {
            colorPo.setColorType(16081001);
        } else if ("内饰".equals(colorType)) {
            colorPo.setColorType(16081002);
        } else {
            throw new ServiceBizException("颜色类型不存在");
        }
        colorPo.setColorCode(rowDto.getColorCode());
        colorPo.setColorName(rowDto.getColorName());

        if (isValidateSucess) {
            colorMapper.insert(colorPo);
        }
    }

    /**
     * 颜色导入模板下载
     *
     * @return void
     * @author caozx
     * @since 2020/12/10
     */
    @Override
    public void export(HttpServletResponse response) throws IOException{
        List<ColorsVO> colorVos = colorMapper.queryColorExport();
        String sheetName = "颜色导入模板";
        String titleName = "颜色导入模板";
        EasyPoiUtil.exportExcelResponse(sheetName, titleName, colorVos, ColorsVO.class, "颜色导入模板", response);
    }

    @Override
    public Map<String,List<ExportMsgVO>> upload(MultipartFile file) {
        //校验文件是否为空
        checkMultipartFile(file);
        //解析成list
        List<ColorsVO> list = EasyPoiUtil.importExcel(file, 1, 1, ColorsVO.class);
        //校验数据信息
        return importList(list);
    }

    /**
     * 校验导入数据并插入数据库
     *
     * @return void
     * @author caozx
     * @since 2020/12/10
     */
    public Map<String,List<ExportMsgVO>> importList(List<ColorsVO> list) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String,List<ExportMsgVO>> errorMap = new HashMap();

        try{
            List<ExportMsgVO> errorList = new ArrayList<>();
            for (int i = 3; i < list.size() + 3; i++) {
                StringBuilder msg = new StringBuilder();
                ExportMsgVO exportMsgVO = new ExportMsgVO();

                String colorCode = list.get(i - 3).getColorCode();
                String colorName = list.get(i - 3).getColorName();
                String colorType = list.get(i - 3).getColorType();
                String isValid = list.get(i - 3).getIsValid();
                if ("内饰".equals(colorType)) {
                    colorType = "16081001";
                } else if ("外饰".equals(colorType)) {
                    colorType = "16081002";
                } else {
                    colorType = null;
                    msg.append("请输入正确的 颜色类型[内饰/外饰]");
                }

                if ("是".equals(isValid)) {
                    isValid = "10041001";
                } else if ("否".equals(isValid)) {
                    isValid = "10041002";
                } else {
                    isValid = null;
                    msg.append("请输入正确的 启用标记[是/否]");
                }

                if(colorCode.length() != 3){
                    msg.append("颜色代码为三位");
                }
                Map<String, Object> map = colorMapper.ifExist(colorCode,colorName,colorType);
                if (null != map) {
                    msg.append("颜色代码+名称 在系统中已存在;");
                }
                if (StringUtils.isNotEmpty(msg)) {
                    exportMsgVO.setRowNO(i);
                    exportMsgVO.setErrorMsg(msg.toString());
                    errorList.add(exportMsgVO);
                }
            }


             if (errorList != null && errorList.size() != 0) {
                errorMap.put("errorList",errorList);
                return errorMap;
            }else {
                //数据库插入操作
                AtomicInteger num = new AtomicInteger(3);
                list.forEach(color->{
                    ColorPO po = new ColorPO();
                    po.setAppId(loginInfoDto.getAppId());
                    po.setOwnerCode(loginInfoDto.getGroupCode());
                    po.setCompanyCode(loginInfoDto.getCompanyCode());
                    po.setOwnerParCode(loginInfoDto.getOwnerParCode());
                    po.setDataSources(BasedataDictConstants.DATA_SOURCES_BY_SUPER);

                    BeanUtil.copyProperties(color,po);
                    if ("是".equals(color.getIsValid())) {
                        po.setIsValid(10041001);
                    } else if ("否".equals(color.getIsValid())) {
                        po.setIsValid(10041002);
                    } else {
                        po.setIsValid(null);
                    }
                    if ("内饰".equals(color.getColorType())) {
                        po.setColorType(16081001);
                    } else if ("外饰".equals(color.getColorType())) {
                        po.setColorType(16081002);
                    } else {
                        po.setColorType(null);
                    }
                    colorMapper.insert(po);

                    ExportMsgVO exportMsgVO = new ExportMsgVO();
                    exportMsgVO.setRowNO(num.getAndIncrement());
                    exportMsgVO.setErrorMsg("成功");
                    errorList.add(exportMsgVO);
                    errorMap.put("errorList",errorList);
                });
                return errorMap;
            }


        } catch (IllegalArgumentException e) {
            log.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage());
        }
    }

    /**
     * 校验文件是否为空
     *
     * @param file 上传文件
     * @author caozx
     * @date 2021/01/08
     */
    public void checkMultipartFile(MultipartFile file) {
        try {
            Assert.notNull(file, "导入模版必传！");
            Assert.notEmpty(file.getOriginalFilename(), "模版必须有文件名！");
            String filename = file.getOriginalFilename();
            String type = filename.substring(filename.lastIndexOf("."));
            Assert.isTrue(org.apache.commons.lang3.StringUtils.equals(type, ".xlsx")||org.apache.commons.lang3.StringUtils.equals(type, ".xls"), "导入表格必须是xlsx或xls文件！");
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage());
        }
    }
}
